package logic

import (
	"context"
	"project/pkg"
	"project/projectrpc/projectrpc"

	"project/projectapi/internal/svc"
	"project/projectapi/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserLoginLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUserLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserLoginLogic {
	return &UserLoginLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UserLoginLogic) UserLogin(req *types.UserLoginRequest) (resp *types.Response, err error) {
	// todo: add your logic here and delete this line

	_, err = l.svcCtx.ProjectRpc.VailUser(l.ctx, &projectrpc.VailUserRequest{
		Tel:     req.Tel,
		Source:  "login",
		Captcha: req.Captcha,
		SendSms: req.SendSms,
	})
	if err != nil {
		return &types.Response{
			Message:  pkg.String(err.Error()),
			Code:     500,
			Database: nil,
		}, nil
	}

	login, err := l.svcCtx.ProjectRpc.UserLogin(l.ctx, &projectrpc.UserLoginRequest{
		Tel:      req.Tel,
		Password: req.Password,
	})
	if err != nil {
		return &types.Response{
			Message:  pkg.String(err.Error()),
			Code:     500,
			Database: nil,
		}, nil
	}

	login1, _ := pkg.TokenHandler(int(login.Id))

	return &types.Response{
		Message:  "登录成功",
		Code:     200,
		Database: login1,
	}, nil
}
